package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.WmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper,WmChannel> implements WmChannelService {

    /**
     * 根据名称分页查询频道列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //构建查询条件
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        //判断前端传入的频道名称是否为空，不为空的话添加查询条件
        if (!StringUtils.isEmpty(dto.getName())){
            query.like(WmChannel::getName,dto.getName());
        }
        //构建分页条件
        Page<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        Page<WmChannel> ipage = this.page(page, query);
        //给前端返回通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),ipage.getTotal(),ipage.getRecords());
        return result;
    }

    /**
     * 频道新增
     * @param channel
     * @return
     */
    @Override
    public ResponseResult<Integer> addChannel(WmChannel channel) {
        //判断频道是否存在，如果存在就不新增
        if (channel == null || StringUtils.isEmpty(channel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //根据频道名称查询数据库表记录
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,channel.getName());
        int count = this.count(query);
        //如果存在，提示数据已存在
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);//数据已存在
        }
        //不存在，就存到表中
        //设置创建时间
        channel.setCreatedTime(new Date());
        this.save(channel);
        //返回结果
        return null;
    }
}
